package cn.hd01.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import cn.hd01.repository.entity.Banner;
import cn.hd01.service.BannerService;
import cn.hd01.web.auth.Auth;

@Auth
@Controller
@RequestMapping("/banner")
public class BannerController {

	@Autowired
	private BannerService service;

	@RequestMapping(path = "/type/{type}", method = RequestMethod.GET)
	public String index(@PathVariable("type") Integer type, Model m) {
		m.addAttribute("type", type);
		return "banner";
	}

	@ResponseBody
	@RequestMapping(path = "/list/{type}", method = RequestMethod.GET)
	private Page<Banner> find(@PathVariable("type") Integer type, @PageableDefault Pageable pageable) {
		return service.findByType(type, pageable);
	}
	
	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void find(@PathVariable("id") Integer id) {
		service.delete(id);
	}
	
	@ResponseBody
	@RequestMapping(path = "/seq", method = RequestMethod.POST)
	private void updateSeq(Integer pk, Integer value) {
		Banner banner = service.findOne(pk);
		banner.setSeq(value);
		service.save(banner);
	}

	@ResponseBody
	@RequestMapping(path = "/set/{type}", method = RequestMethod.GET)
	private void set(@PathVariable("type") Integer type, Integer refId, Integer imageId){
		Banner banner = service.findByTypeAndRefId(type, refId);
		if (banner == null){
			banner = new Banner(type, refId, imageId);
		} else {
			banner.setImgId(imageId);
		}

		service.save(banner);
	}

}
